import React, { Fragment, PureComponent } from 'react';
import { connect } from 'dva';
import { routerRedux, Link } from 'dva/router';
import moment from 'moment';
import { map, pull, indexOf } from 'lodash';
import ZubieForm from './components/ZubieForm'
import PhaseForm from './components/PhaseForm'

import {
  Form,
  Input,
  Select,
  InputNumber,
  Button,
  Card,
  Radio,
  Checkbox,
  Table,
  Modal,
  Popconfirm,
  message,
  Tooltip
} from 'antd';
const RadioGroup = Radio.Group;
const Option = Select.Option;

const FormItem = Form.Item;
const { TextArea } = Input;

@connect(({ gameProject, zubie, loading }) => ({
  gameProject, zubie,
  submitting: loading.effects['gameProject/addGameProject'],
}))
@Form.create()
export default class ZubieList extends PureComponent {
  state = {
    modalVisible: false,
    curProject: {},
  };

  componentDidMount = () => {
    const { dispatch, location } = this.props;
    const pathArray = location.pathname.split('/');
    const id = pathArray[3];
    this.setState({
      id,
    });
    dispatch({
      type: 'gameList/findById',
      payload: id,
      callback: () => {
        dispatch({
          type: 'gameProject/findGameProject',
        });
      },
    });

    dispatch({
      type: 'gameProject/findProjectDict',
    });
  };

  renderProjectDict = () => {
    const { projectDictList } = this.props.gameProject;
    return map(projectDictList, data => (
      <Checkbox
        key={`ck-${data.code}`}
        checked={this.containsCode(data.code)}
        onChange={e => this.onProjectDictChange(data.code, e)}
      >
        {data.pName}
      </Checkbox>
    ));
  };

  containsCode = code => {
    const { gameProjectList } = this.props.gameProject;
    var flag = false;
    gameProjectList.forEach(element => {
      if (element.projectCode === code && element.status === 'N') flag = true;
    });
    return flag;
  };

  onProjectDictChange = (code, e) => {
    const checked = e.target.checked;
    if (checked) {
      this.props.dispatch({
        type: 'gameProject/addGameProject',
        payload: { projectCode: code },
      });
    } else {
      this.props.dispatch({
        type: 'gameProject/removeGameProject',
        payload: { projectCode: code },
      });
    }
  };

  showAddModal = data => {
    const { projectDictMap } = this.props.gameProject;

    this.setState({
      modalVisible: true,
      formhandle: this.handleAdd,
      curProject: { ...data, projectName: projectDictMap[data.projectCode].pName },
    });
  };

  showPhaseAddModal = data => {
    this.setState({
      phaseModalVisible: true,
      phaseHandle: this.phaseHandleAdd,
      modifyPhaseZubieCode: data.code,
    });
  };

  showModifyModal = data => {
    const { projectDictMap } = this.props.gameProject;
    this.setState({
      modalVisible: true,
      formhandle: this.handleModify,
      curProject: { projectCode: data.projectCode, projectName: projectDictMap[data.projectCode].pName },
      curData: data,

    });
  };

  showPhaseModifyModal = data => {
    this.setState({
      phaseModalVisible: true,
      phaseHandle: this.handlePhaseModify,
      curPhase: data,
      gameMethod: data.gameMethod,
    });
  }

  handleModify = fields => {
    this.props.dispatch({
      type: 'zubie/modifyZubie',
      payload: fields,
      callback: () => {
        this.handleModalVisible();
      }
    });

  };

  handlePhaseModify = fields => {
    this.props.dispatch({
      type: 'phase/modifyPhase',
      payload: fields,
      callback: () => {
        this.phaseHandleModalVisible()
      }
    });
  }

  handleModalVisible = flag => {
    this.setState({
      modalVisible: !!flag,
      curProject: {},
      curData: null,
    });

  };

  phaseHandleModalVisible = flag => {
    this.setState({
      phaseModalVisible: !!flag,
      curZubie: {},
      curPhase: null,
      gameMethod: null,
    });
  }

  handleAdd = fields => {
    fields.status = 'N';
    fields.enabled = true;
    this.props.dispatch({
      type: 'zubie/addZubie',
      payload: fields,
    });
    this.handleModalVisible();
  };

  phaseHandleAdd = fields => {
    this.props.dispatch({
      type: 'phase/addPhase',
      payload: fields,
    });
    this.phaseHandleModalVisible();
  };

  closeProjectZubie = item => {
    this.props.dispatch({
      type: 'zubie/closeGameProjectZubie',
      payload: item.id,
    });
  };

  openProjectZubie = item => {
    this.props.dispatch({
      type: 'zubie/openProjectZubie',
      payload: item.id,
    });
  };

  handlePublicChange = e => {
    this.setState({
      isPublic: e.target.value,
    });
  };

  deletePhase = (zubieCode, phaseId) => {
    this.props.dispatch({
      type: 'zubie/deletePhase',
      payload: {
        zubieCode,
        phaseId,
      },
      callback: () => {
        message.success('阶段删除成功')
      }
    });
  }

  expandedRowRender = (record, index) => {
    const columns = [
      { title: '阶段名称', dataIndex: 'name', key: 'phase_name' },
      { title: '序号', dataIndex: 'seq', key: 'phase_seq' },
      {
        title: '比赛方式', dataIndex: 'gameMethod', key: 'phase_game_method',
        render: (value) => {
          switch (value) {
            case 'FENZU':
              return <span>分组循环</span>
            case 'OUT':
              return <span>单淘汰赛</span>
            case 'CYCLE':
              return <span>单循环赛</span>
            case 'SCORE':
              return <span>循环积分</span>
            default:
              return <span>未知</span>
          }
        }
      },
      {
        title: '种子数',
        dataIndex: 'seedCount',
        width: 60,
      },
      {
        title: '入位方式', dataIndex: 'riseMethod', key: 'phase_rise_method',
        render: (value) => {
          switch (value) {
            case 'CHOUQIAN':
              return <span>抽签</span>
            case 'B_CROSS':
              return <span>大交叉</span>
            case 'S_CROSS':
              return <span>小交叉</span>
            default:
              return <span>未设置</span>
          }
        }
      },
      { title: '局数', dataIndex: 'gameNum', key: 'phase_game_num' },
      { title: '分制', dataIndex: 'gameWinScore', key: 'game_win_score' },
      { title: '每小组人数', dataIndex: 'perFenzuCount', key: 'per_fenzu_count' },
      { title: '晋级人数', dataIndex: 'perFenzuWins', key: 'per_fenzu_wins' },
      {
        title: '操作',
        width: 170,
        key: 'operation',
        render: (value, item) => (
          <div>
            <Button style={{ marginRight: 5 }} onClick={() => {
              item.zubieStatus = record.status
              this.showPhaseModifyModal(item)
            }
            }>
              编辑
              </Button>
            <Tooltip placement="topLeft" title="比赛开始进行编排后不能再修改" arrowPointAtCenter>
              <Popconfirm
                title="是否确定删除阶段?"
                onConfirm={() => this.deletePhase(record.code, item.id)}
              >
                <Button disabled={record.status && record.status !== 'NEW'}>删除</Button>
              </Popconfirm>
            </Tooltip>
          </div>
        ),
      },
    ];

    return (
      <Table
        size='small'
        columns={columns}
        dataSource={record.phaseList}
        pagination={false}
      />
    );
  };

  render() {
    const { submitting } = this.props;
    const { gameProjectList, projectDictMap, gameProjectZubie } = this.props.gameProject;
    const { modalVisible, phaseModalVisible, curProject, curData, curPhase } = this.state;

    const zubieMethod = {
      handleAdd: this.state.formhandle,
      handleModalVisible: this.handleModalVisible,
    };

    const phaseMethod = {
      handleAdd: this.state.phaseHandle,
      handleModalVisible: this.phaseHandleModalVisible,
    };

    const columns = [
      {
        title: '组别名称',
        dataIndex: 'zubieName',
        width: 200,
      },
      {
        title: '最大人数',
        dataIndex: 'signMax',
        width: 80,
      },
      {
        title: '比赛时间段',
        dataIndex: 'timePhase',
        width: 120,
        render: value => {
          switch (value) {
            case 'one':
              return <span>全天</span>;
            case 'two':
              return <span>上午/下午</span>;
            case 'three':
              return <span>上午/下午/晚上</span>;
          }
        },
      },
      {
        title: '状态',
        dataIndex: 'status',
        width: 60,
        render: value => {
          switch (value) {
            case 'N':
              return <span>正常</span>;
            case 'D':
              return <span>已关闭</span>;
          }
        },
      },
      {
        title: '比赛方式',
        width: 90,
        dataIndex: 'gameMethod',
        render: value => {
          switch (value) {
            case 'SC':
              return <span>单循环赛</span>;
            case 'SO':
              return <span>单淘汰赛</span>;
            case 'CO':
              return <span>阶段赛</span>;
            /*case 'MA':
              return <span>自定义</span>;
            case 'TH':
              return <span>三场制</span>;
            case 'FI':
              return <span>五场制</span>;*/
          }
        },
      },
      {
        title: '决出名次',
        dataIndex: 'rankingCount',
        width: 90,
      },
      {
        title: '参赛条件',
        dataIndex: 'signCondition',
        render: value => <div>{value}</div>,
      },
      {
        title: '操作',
        width: 250,
        render: (value, item) =>
          item.enabled ? (
            <div>
              <Tooltip placement="topLeft" title="阶段赛可以添加分组，但比赛开始进行编排后不能再添加" arrowPointAtCenter>
                <Button disabled={item.status !== 'NEW' || item.gameMethod !== 'CO'} style={{ marginRight: 5 }} onClick={() => this.showPhaseAddModal(item)}>
                  添加阶段
                </Button>
              </Tooltip>
              <Tooltip placement="topLeft" title="比赛开始进行编排后不能再修改" arrowPointAtCenter>
                <Button disabled={item.status !== 'NEW'} style={{ marginRight: 5 }} onClick={() => this.showModifyModal(item)}>
                  编辑
              </Button>
              </Tooltip>
              <Tooltip placement="bottomLeft" title="关闭组别不会删除组别，只是不能再编排和继续比赛，你可以在需要时开启" arrowPointAtCenter>
                <Popconfirm
                  title="是否确定关闭组别？"
                  onConfirm={() => this.closeProjectZubie(item)}
                >
                  <Button>关闭</Button>
                </Popconfirm>
              </Tooltip>
            </div>
          ) : (
              <Button onClick={() => this.openProjectZubie(item)}>开启</Button>
            ),
      },
    ];

    const ProjectDetail = () => {
      return map(
        gameProjectList,
        data =>
          data.status === 'N' && (
            <Card
              extra={
                <Button onClick={() => this.showAddModal(data)} type="primary">
                  {`为【${projectDictMap[data.projectCode].pName}】项目添加组别`}
                </Button>
              }
              style={{ width: '100%', marginTop: 5 }}
              bordered={true}
              title={projectDictMap[data.projectCode].pName}
            >
              <Table
                bordered
                size="small"
                dataSource={gameProjectZubie[data.code] ? gameProjectZubie[data.code] : []}
                columns={columns}
                pagination={false}
                expandedRowRender={this.expandedRowRender}
                defaultExpandAllRows={true}
              />
            </Card>
          )
      );
    };

    const formItemLayout = {
      labelCol: {
        xs: { span: 24 },
        sm: { span: 7 },
      },
      wrapperCol: {
        xs: { span: 24 },
        sm: { span: 12 },
        md: { span: 10 },
      },
    };

    const submitFormLayout = {
      wrapperCol: {
        xs: { span: 24, offset: 0 },
        sm: { span: 10, offset: 7 },
      },
    };

    return (
      <Fragment>
        <Card bordered={true} title="请选择此赛事包含的比赛项目">
          {this.renderProjectDict()}
        </Card>
        <div style={{ display: 'flex', flexWrap: 'wrap', marginTop: 10 }}>
          <ProjectDetail />
        </div>

        <ZubieForm
          {...zubieMethod}
          modalVisible={modalVisible}
          curProject={curProject}
          curData={curData}
        />
        <PhaseForm
          {...phaseMethod}
          modalVisible={phaseModalVisible}
          curData={curPhase}
          zubieCode={this.state.modifyPhaseZubieCode}
        />
      </Fragment>
    );
  }
}
